<template>
  <div class="navigation-bar">
    <div class="container">
      <!-- 搜索框和logo -->
      <div class="logo-search">
        <form class="search" @submit.prevent="submitSearchResultHandler">
          <input type="text" placeholder="男式V领小羊绒衫 限时8折" v-model="searchWord">
          <button type="submit" class="iconfont icon-sousuo1"></button>
        </form>
        <span class="iconfont icon-gouwuche">
          <span class="number">10</span>
        </span>
      </div>
    </div>
    <div class="nav-container" :class="{ 'fixed': fixed, 'mar-40': !fixed }">
      <div class="container">
        <div class="logo" v-if="fixed"></div>
        <!-- 导航条 -->
        <ul class="navigation container">
          <li :class="{ active: selectedIndex === 0 }">
            <a href="/">首页</a>
          </li>
          <li v-for="(nav, index) in navList" :key="nav.id" :class="{ active: selectedIndex === index + 1 }">
            <a href="javascript: void(0)" @click="recordCurrentCatogoryHandler(0, index, nav)">{{ nav.name }}</a>
            <!-- 类目 -->
            <div class="category" :style="{left: '-' + nav.left + 'px'}">
              <div class="sub-cate-item" v-for="subCateitem in nav.children" :key="subCateitem.id">
                <h1>{{ subCateitem.name }}</h1>
                <ul>
                  <li v-for="item in subCateitem.children" :key="item.id" @click="recordCurrentCatogoryHandler(1, index, nav, subCateitem)">
                    <img :src="item.advImg" :alt="item.name"> {{ item.name }}
                  </li>
                </ul>
              </div>
            </div>
            <!-- 向上箭头 -->
            <div class="arrow"></div>
          </li>
          <li :class="{ active: selectedIndex === navList.length }" v-if="!fixed">
            <a href="#">为你严选</a>
            <span class="line"></span>
          </li>
          <li :class="{ active: selectedIndex === navList.length }" v-if="!fixed">
            <a href="#">众筹</a>
          </li>
        </ul>
      </div>
    </div>
    <!-- 占位div -->
    <div class="seize-seat" v-if="fixed"></div>
  </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'
import { CONTAINER_WIDTH } from '@/config'

// 导入jquery
import $ from 'jquery'

export default {
  data () {
    return {
      searchWord: '',
      selectedIndex: 0,
      navList: [],
      padWidth: 24,
      startWidth: 76,
      fixed: false
    }
  },

  async created () {
    // 获取接口
    this.getCategoryInfo(() => {
      // 将数据保存到全局作用域中
      this.navList = this.category
      this.navList.forEach((nav, index) => {
        if (nav.id === Number(this.$route.params.categoryId)) {
          this.selectedIndex = index + 1
        }
      })
      // 等页面渲染完成计算
      this.$nextTick(() => {
        this.calcNavigationCategoryOffset()
        this.watchWindowScroll()
      })
    })
  },

  computed: {
    ...mapGetters(['category'])
  },

  methods: {
    ...mapActions(['getCategoryInfo', 'setCateInfo']),
    /**
     * 点击提交结果
     */
    submitSearchResultHandler () {
      // 如果没有输入搜索的字段
      if (!this.searchWord) {
        return
      }
      console.log('您输入的字符是：', this.searchWord)
    },

    /**
     * 计算导航条分类属性的偏移量
     */
    calcNavigationCategoryOffset () {
      // 如果没有获取到导航条长度
      if (!this.navList || this.navList.length === 0) {
        return
      }
      // 左偏移量
      let offsetLeft = this.startWidth
      // 设置左偏移长度
      this.navList.forEach((nav, index) => {
        // 取出孩子节点
        const subCateGroupList = nav.children || []
        // 分类属性的长度
        const offsetWidth = (180 * subCateGroupList.length + 40)

        // 如果当前分类宽度超过容器最大限度
        if (CONTAINER_WIDTH <= offsetWidth) {
          nav.left = (offsetWidth - CONTAINER_WIDTH) / 2 + offsetLeft
        } else {
          // 设置左偏移量
          nav.left = offsetWidth / 2
          // 如果当前左偏移量超过左边限制，但是分类属性的长度没有超过容器宽度，则使用左边的限制
          if (nav.left > offsetLeft) {
            nav.left = offsetLeft
          }
        }

        // 重新设置起点
        offsetLeft += this.padWidth * 2 + $(`.navigation > li:eq(${index + 1})`).width()
      })
    },

    /**
     * 记录当前点击的分类
     * @param { Number } level 当前是第几级
     * @param { Object } nav   当前导航对象
     * @param { Number } index 当前点击的第几个分类
     * @param { Number } child 子分类
     */
    recordCurrentCatogoryHandler (level, index, nav, child) {
      this.selectedIndex = index + 1
      // this.setCateInfo(nav)
      // 如果是第一级
      if (level === 0) {
        this.$router.push(`/category/${nav.id}`)
        return
      }
      this.$router.push(`/category/${nav.id}/${child.id}`)
    },

    /**
     * 监听屏幕滚动时间
     */
    watchWindowScroll () {
      const _this = this
      $(document).scroll(function () {
        // 滚动的高度
        const scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop
        // 如果当前是滚动超过了菜单的大小
        if (scrollTop > 200) {
          _this.fixed = true
          return
        }
        _this.fixed = false
      })
    }
  }
}
</script>

<style lang="less" scoped>
@import "../../styles/variable";
.navigation-bar {
  box-shadow: 0 0 3px 0 rgba(0, 0, 0, .2);
  .logo-search {
    align-items: flex-end;
    background-image: url();
    background-repeat: no-repeat;
    background-position: bottom center;
    background-size: auto 54%;
    display: flex;
    justify-content: flex-end;
    height: 120px;
    width: 100%;
    .search {
      display: inline-block;
      height: 30px;
      input {
        border: 0px;
        border-bottom: 1px solid @line-color-golden;
        outline: none;
        padding: 6px 10px
      }
    }
    button {
      background: @write;
      border: 0px;
      outline: none;
    }
    .iconfont {
      color: @font-color-golden;
      cursor: pointer;
      display: inline-block;
      font-size: 20px;
      width: 27px;
      height: 27px;
      &.icon-gouwuche {
        display: inline-block;
        margin-left: 20px;
        position: relative;
        .number {
          background-color: @color-warning;
          border-radius: 10px;
          color: @write;
          font-size: 12px;
          padding: 0px 4px;
          position: absolute;
          height: 16px;
          top: -6px;
          left: 12px;
        }
      }
    }
  }
  .nav-container {
    background: @write;
    position: relative;
    width: 100%;
    z-index: 10;
    .container {
      align-items: center;
      display: flex !important;
      .logo {
        background-image: url('');
        background-size: 100% 100%;
        height: 36px;
        width: 106px;
        margin-right: 20px;
      }
      .navigation {
        li {
          cursor: pointer;
          display: inline-block;
          font-size: 14px;
          font-weight: 700;
          padding: 20px 24px;
          text-align: center;
          position: relative;
          a {
            color: @black;
            text-decoration: none;
          }
          .line {
            background-color: @line-color-light;
            display: inline-block;
            width: 1px;
            height: 20px;
            position: absolute;
            left: 0px;
            top: 20px;
          }
          &:hover {
            a {
              border-bottom: 3px solid @font-color-golden;
              color: @font-color-golden;
            }
            .category {
              display: flex;
            }
            .arrow {
              display: block;
            }
          }
          &.active {
            a {
              border-bottom: 3px solid @font-color-golden;
              color: @font-color-golden;
            }
          }
          .category {
            background: @write;
            box-shadow: 0 0 1px 1px @box-color-light;
            display: none;
            flex-direction: row;
            padding: 20px 20px 30px;
            position: absolute;
            top: 59px;
            z-index: 1;
            .sub-cate-item {
              display: inline-block;
              width: 140px;
              text-align: left;
              margin: 0px 20px;
              h1 {
                border-bottom: 1px solid @line-color-golden;
                font-size: 16px;
                font-weight: 700;
                padding: 8px 0px;
              }
              ul {
                margin-top: 10px;
                li {
                  align-items: center;
                  color: @font-color;
                  display: flex;
                  font-weight: 400;
                  height: 60px;
                  margin: 0px;
                  padding: 0px;
                  text-align: left;
                  img {
                    display: inline-block;
                    width: 50px;
                    height: 50px;
                    margin-right: 6px;
                  }
                  &:hover {
                    color: @font-color-golden;
                    border-bottom: 0px;
                  }
                }
              }
            }
          }
          .arrow {
            border-left: 8px solid transparent;
            border-right: 8px solid transparent;
            border-bottom: 8px solid @box-color-light;
            display: none;
            position: absolute;
            top: 51px;
            left: 30px;
            z-index: 2;
            &:after {
              border-left: 8px solid transparent;
              border-right: 8px solid transparent;
              border-bottom: 8px solid @write;
              content: " ";
              display: block;
              position: absolute;
              top: 1px;
              left: -8px;
            }
          }
        }
      }
    }
    &.mar-40 {
      margin-top: 40px;
    }
    &.fixed {
      box-shadow: 0 0 3px 0 rgba(0, 0, 0, 0.2);
      position: fixed;
      top: 0px;
      li {
        padding: 20px !important;
      }
    }
  }
  .seize-seat {
    height: 100px;
  }
}
</style>
